package br.com.serinus.serinus.app;

import java.lang.reflect.Method;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.ext.Provider;

import org.jboss.resteasy.annotations.interception.RedirectPrecedence;
import org.jboss.resteasy.annotations.interception.ServerInterceptor;
import org.jboss.resteasy.annotations.providers.jaxb.Stylesheet;
import org.jboss.resteasy.core.ServerResponse;
import org.jboss.resteasy.spi.ResteasyProviderFactory;
import org.jboss.resteasy.spi.interception.AcceptedByMethod;
import org.jboss.resteasy.spi.interception.PostProcessInterceptor;

@Provider
@ServerInterceptor
@RedirectPrecedence
public class RequestDispatcherApp implements PostProcessInterceptor, AcceptedByMethod{

	//FIXME log

    public void postProcess(ServerResponse r) {
        String page = "/WEB-INF/" + r.getResourceMethod().getAnnotation(Stylesheet.class).href();
        HttpServletRequest request = ResteasyProviderFactory.getContextData(HttpServletRequest.class);
        HttpServletResponse response = ResteasyProviderFactory.getContextData(HttpServletResponse.class);
        
        // Não deixa o browser guardar o cache
        response.setDateHeader ("Expires", 0); 
        response.setHeader ("Pragma", "no-cache"); 
        if (request.getProtocol ().equals ( "HTTP/1.1" )) {   
        	response.setHeader ("Cache-Control", "no-cache");   
        }  
        
        render(request, response, page);
    }

    /**
     * Redirecionar para outra página
     */
    public static void render(HttpServletRequest r, HttpServletResponse p, String page) {
        RequestDispatcher dd = r.getRequestDispatcher(page);
        if (dd == null) {
            p.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } else {
            try {
                dd.forward(r, p);
            }
            catch (Exception e) {
                p.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
        }
    }

    public boolean accept(@SuppressWarnings ("rawtypes") Class c, Method m) {
        if (m.isAnnotationPresent(Stylesheet.class)
                && m.getAnnotation(Stylesheet.class).type().equals("application/jsp")) {
            return true;
        }
        return false;
    }
}
